<template>
  <div class="oldSailDiv">
    <!--      首页条-->
    <index-header></index-header>

    <!--    网页主体-->
    <el-row
      style="width: 80%; margin: 0 auto; padding-top: 80px; margin-bottom: 40px"
    >
      <el-col>
        <h2>捐赠闲置：</h2>
        <el-card shadow="always">
          <el-form
            label-position="top"
            label-width="80px"
            :model="submitDonationForm"
            :rules="rules"
            ref="submitDonationForm"
          >
            <el-col :span="22" :offset="2">
              <el-form-item label="商品图" enctype="multipart/form-data">
                <!--图片上传组件-->
                <el-upload
                  list-type="picture-card"
                  ref="upload"
                  :action="action"
                  :on-success="submitSuccess"
                  :on-error="submitError"
                  :auto-upload="true"
                  :limit="4"
                  :on-exceed="submitIndexOut"
                  accept="image/*"
                >
                  <i slot="default" class="el-icon-plus"></i>
                  <div slot="file" slot-scope="{ file }">
                    <img
                      class="el-upload-list__item-thumbnail"
                      :src="file.url"
                      alt="请检查网络连接"
                    />
                    <span class="el-upload-list__item-actions">
                      <span
                        class="el-upload-list__item-preview"
                        @click="handlePictureCardPreview(file)"
                      >
                        <i class="el-icon-zoom-in"></i>
                      </span>
                      <span
                        class="el-upload-list__item-delete"
                        @click="handleRemove(file)"
                      >
                        <i class="el-icon-delete"></i>
                      </span>
                    </span>
                  </div>
                </el-upload>
                <el-dialog :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl" alt="" />
                </el-dialog>
              </el-form-item>
            </el-col>

            <el-col :span="5" :offset="2" style="margin-top: 50px">
              <el-form-item label="物品名称" prop="goodName">
                <el-input
                  v-model="submitDonationForm.donationName"
                  maxlength="15"
                  show-word-limit
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" :offset="2" style="margin-top: 50px">
              <el-form-item label="物品位置" prop="goodAddress">
                <el-input
                  v-model="submitDonationForm.donationAddress"
                  placeholder="广州校区29栋"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="4" :offset="2" style="margin-top: 50px">
              <el-form-item label="物品类型" prop="donationCategoryId">
                <el-select
                  v-model="submitDonationForm.donationCategoryId"
                  placeholder="请选择物品类型"
                >
                  <el-option
                    v-for="(category, index) in goodCategory"
                    :key="category.goodCategoryId"
                    :label="category.goodCategory"
                    :value="category.goodCategoryId"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="13" :offset="2" style="margin-top: 20px">
              <el-form-item label="物品介绍" prop="goodDescription">
                <el-input
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 8 }"
                  placeholder="请输入内容"
                  v-model="submitDonationForm.donationDescription"
                  maxlength="100"
                  show-word-limit
                >
                </el-input>
              </el-form-item>
            </el-col>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="5" :offset="9">
        <el-button
          type="primary"
          @click="submitForm('submitDonationForm')"
          style="width: 100%"
          >上传</el-button
        >
      </el-col>
    </el-row>

    <el-dialog :visible.sync="showInfoDialog" width="500px" title="公益捐书|“童”你一起，让爱延续" center>
      <div style="text-align: center">
        
        <img src="http://waiterxiaoyy20200823.oss-cn-shenzhen.aliyuncs.com/IdleImages/1605343904928.jpg" alt="请检查网络连接" width="100%" />
        <p style="text-align: left; margin-top:20px; font-size: 18px">描述：本次活动由广财小站团队发起，响应国家精准扶贫号召，助推中国平安“村教、村医、村官”三村建设工程的落地。以书籍流转为核心，聚焦捐书公益，建设乡村学校图书角。以阅读促进社区连接，促成相伴共读的美好生活风尚；同时，挖掘乡村学校个性化需求，实现精准捐书，以阅读公益助推精准扶贫。</p>
        <p style="text-align: left; font-size: 18px">参与方式：在此捐赠物品，填写详细信息，我们将派人前去搜集物品，并邮寄到公益服务对象所在地，您可在个人中心中查看到自己捐赠物品的情况。</p>

        <span slot="footer" class="dialog-footer">
          <el-button
            type="success"
            style="margin-top: 30px"
            @click="showInfo"
          >我已知悉</el-button>
          
        </span>
      </div>
    </el-dialog>
    <!--弹出提示框-->
    <el-dialog
      title="提示"
      :visible.sync="centerDialogVisible"
      width="30%"
      center
    >
      <div style="text-align: center">
        <h4>{{ dialogValue }}</h4>
        <span slot="footer" class="dialog-footer">
          <el-button
            type="primary"
            @click="clickButton"
            style="margin-top: 30px"
            >确 定</el-button
          >
        </span>
      </div>
    </el-dialog>

    <!--      首页尾-->
    <index-footer></index-footer>
  </div>
</template>

<script>
import IndexHeader from "./pages/index-header";
import IndexFooter from "./pages/index-footer";

export default {
  name: "donationIdle",
  data() {
    let checkPrice = (rule, value, callback) => {
      let numberRex = /^([1-9]\d*(\.\d*[1-9])?)|(0\.\d*[1-9])$/;
      if (value === "") {
        return callback(new Error("商品价格不能为空"));
      } else {
        if (!numberRex.test(value)) {
          callback(new Error("请输入正数"));
        } else {
          if (value < 0) {
            callback(new Error("必须大于 0"));
          } else {
            callback();
          }
        }
      }
    };

    let checkString = (rule, value, callback) => {
      if (!value) {
        return callback(new Error("请填写内容"));
      } else {
        callback();
      }
    };
    return {
      submitDonationForm: {
        donationId: "",
        donationName: "",
        donationAddress: "",
        donationDescription: "",
        userId: "",
        donationCategoryId: "",
      },
      goodCategory: [],
      dialogImageUrl: "",
      dialogVisible: false,
      disabled: false,
      showInfoDialog: true,
      dialogValue: "",
      centerDialogVisible: false,
      action: "",
      rules: {
        donationName: [{ validator: checkString, trigger: "blur" }],
        donationDescription: [{ validator: checkString, trigger: "blur" }],
      },
    };
  },
  components: {
    IndexHeader,
    IndexFooter,
  },
  created() {
    let self = this;
    $.get(
      "http://waiterxiaoyy.free.idcfengye.com/web/getGoodsCategory",
      function (data) {
        self.goodCategory = data.data;
      },
      "json"
    );
  },
  mounted() {
    //先从服务端获取一个随机不重复的商品ID作为准备新上传的闲置商品ID
    let self = this;
    $.get(
      "http://waiterxiaoyy.free.idcfengye.com/web/getdonationid",
      function (data) {
        self.submitDonationForm.donationId = data.data[0];
        //设置上传图片路径，需要一个商品ID
        self.action =
          "http://waiterxiaoyy.free.idcfengye.com/web/donation/uploadImage?donationid=" +
          data.data[0];
      },
      "json"
    );
  },
  methods: {
    showInfo() {
      this.showInfoDialog = false;
    },
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // alert('submit!');
          if (this.$refs.upload.uploadFiles.length === 0) {
            this.$message.error("请上传商品图片");
          } else {
            let self = this;
            this.submitDonationForm.userId = window.sessionStorage.getItem(
              "userId"
            );
            let jsonMsg = JSON.stringify(this.submitDonationForm);
            $.post(
              "http://waiterxiaoyy.free.idcfengye.com/web/addDonation",
              jsonMsg,
              function (data) {
                if (data.code === 200) {
                  self.$message.success(data.msg);
                  self.$router.push("/person#personOldId")
                } else {
                  self.$message.error(data.msg);
                }
              },
              "json"
            );
          }
        } else {
          // console.log('error submit!!');
          return false;
        }
      });
    },
    clickButton() {
      this.centerDialogVisible = false;
      let self = this;
      if (this.dialogValue === "保存成功") {
        setTimeout(function () {
          self.$router.push("/person#personOldId");
        }, 1000);
      }
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleRemove(file) {
      let fileList = this.$refs.upload.uploadFiles;
      let index = fileList.findIndex((fileItem) => {
        return fileItem.uid === file.uid;
      });
      fileList.splice(index, 1);
    },
    submitUpload() {
      console.log(this.$refs.upload.uploadFiles.length);
    },
    submitSuccess() {
      // console.log("成功")
      this.$notify({
        title: "提示",
        message: "图片上传成功",
        duration: 2000,
      });
    },
    submitError() {
      // console.log("失败")
      this.dialogValue = "图片上传失败，请检查网络连接";
      this.centerDialogVisible = true;
    },
    submitIndexOut() {
      this.dialogValue = "图片数量超限";
      this.centerDialogVisible = true;
    },
  },
};
</script>

<style scoped>
h2 {
  font-weight: 400;
  color: #1f2f3d;
  font-size: 28px;
}
</style>
